/****************************************************************************************
 Copyright © 2003-2012 ZTEsoft Corporation. All rights reserved. Reproduction or       <br>
 transmission in whole or in part, in any form or by any means, electronic, mechanical <br>
 or otherwise, is prohibited without the prior written consent of the copyright owner. <br>
 ****************************************************************************************/
package com.iwhalecloud.bss.kite.cucc.web.controller.scene;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;


import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneAdditionalOfferInstService;
import com.iwhalecloud.bss.kite.cucc.service.util.ChangeTypeUtils;
import com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr.IPersonAttrDealService;
import com.iwhalecloud.bss.kite.manager.inst.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.ProdAttrModuleVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IBusinessChangeService;
import com.iwhalecloud.bss.kite.cucc.common.util.KiteAssert;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.transaction.KiteTransactional;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * <Description> <br>
 *
 * @author tengg<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2021年3月3日 <br>
 * @since R9.0<br>
 * @see com.iwhalecloud.bss.kite.cucc.web.controller.scene <br>
 */
@RestController("cuccSceneProductChange")
@RequestMapping("/cuccSceneProductChange")
@Api(tags = {"/cuccSceneProductChange - 多场景变更受理，"
}, description = "初始化在SceneInitController")
public class SceneProductChangeController {

    @Autowired
    private IBusinessChangeService businessChangeService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private OperateInstAttrService operateInstAttrService;

    @Autowired
    private IPersonAttrDealService personAttrDealService;

    @Autowired
    private IOperateSceneAdditionalOfferInstService operateSceneAdditionalOfferInstService;

    @KiteTransactional
    @ApiOperation(value = "二次业务产品类场景初始化", notes = "二次业务产品类场景初始化，返回场景实例标识")
    @ApiImplicitParams({@ApiImplicitParam(name = "accNum", value = "服务号码"),
        @ApiImplicitParam(name = "prodId", value = "产品实例ID", required = false),
        @ApiImplicitParam(name = "currentServiceOfferId", value = "当前操作类型", required = false),
        @ApiImplicitParam(name = "sceneInstId", value = "场景实例ID", required = true),
        @ApiImplicitParam(name = "serviceOfferIds", value = "已勾选的操作类型", required = true)
    })
    @GetMapping("/secondary/initBusinessChangeScene")
    public DataResult<Boolean> initBusinessChangeScene(@RequestParam(required = false) String accNum,
                                                           @RequestParam String prodId, @RequestParam String currentServiceOfferId, @RequestParam String sceneInstId,
                                                           @RequestParam List<String> serviceOfferIds,@RequestParam(required = false) String offerId) {

        LinkedHashSet<String> hashSet = new LinkedHashSet<>(serviceOfferIds);
        serviceOfferIds = new ArrayList<>(hashSet);
        //校验操作类型互斥逻辑
        businessChangeService.checkSceneMutex(currentServiceOfferId, serviceOfferIds);
        if (KiteStringUtils.isNotEmpty(sceneInstId)) {
            KiteAssert.notBlank(accNum, ErrorConsts.ACCNUM_EMPTY);
        }

        operateSceneInstService.putExtParameter(sceneInstId, "BUSI_CHANGE_SERVICEOFFERID", serviceOfferIds);
        // currentServiceOfferId 不在serviceOfferIds里面的时候，认为是取消操作,取消操作时，需要将对应的属性还原为初始值
        if (!serviceOfferIds.contains(currentServiceOfferId)) {
            String custId = KiteWebContext.getContext().getCustId();
            List<KiteInst> kiteProdInsts = querySceneInstService.listInsts(sceneInstId, Collections.singletonList(InstType.PROD_INST));
            kiteProdInsts.forEach(kiteProdInst -> {
                ProdAttrModuleVO prodAttrModule = new ProdAttrModuleVO();
                KiteProdInst prodInst = querySceneInstService.getProdInst(custId, kiteProdInst.getInstId());
                // 获取变更的属性
                prodAttrModule = businessChangeService
                    .dealProdAttrList(sceneInstId, custId, prodInst, currentServiceOfferId, prodAttrModule);

                if (KiteListUtils.isNotEmpty(prodAttrModule.getProdAttrList())) {
                    List<KiteAttr> prodInstAttrs = prodInst.listAttrs();
                    prodAttrModule.getProdAttrList().forEach(prodAttr ->{
                        KiteAttr instAttr = prodInstAttrs.stream().filter(prodInstAttr -> KiteStringUtils.isEqual(prodInstAttr.getFieldName(), prodAttr.getFieldName())).findFirst().orElse(null);
                        if (Objects.nonNull(instAttr) && !KiteStringUtils.isEqual(instAttr.getOriginValue(), instAttr.getValue())) {
                            operateInstAttrService.setAttrValue(prodInst, instAttr.getFieldName(), instAttr.getOriginValue(), sceneInstId, null);
                        }
                    });
                }
            });

            if(KiteStringUtils.equalsAny(currentServiceOfferId, "1009", "1080")) {
                // 还原资费
                List<KiteInst> additionalOffers = querySceneInstService.listInsts(sceneInstId, Collections.singletonList(InstType.ADDITIONAL_OFFER_INST));
                Map<String, String> initFeeOfferActionMap = (Map<String, String>) Optional.ofNullable(querySceneInstService.getExtParameterValue(sceneInstId, "initFeeOfferActionMap")).orElse(new HashMap<>());
                if(KiteListUtils.isNotEmpty(additionalOffers)) {
                    additionalOffers.forEach(kiteInst -> {
                        if(initFeeOfferActionMap.containsKey(kiteInst.getInstId())) {
                            kiteInst.setActionType(ChangeTypeUtils.getActionType(initFeeOfferActionMap.get(kiteInst.getInstId())));
                            kiteInst.listAttrs().forEach(attr -> {
                                attr.setValue(attr.getOriginValue());
                                attr.setValueDesc(attr.getOriginValue());
                                if(KiteStringUtils.isEqual(attr.getShowType(), "98A")) {
                                    String valueDesc = attr.getAttrValues().stream().filter(kiteAttrValue -> KiteStringUtils.isEqual(attr.getOriginValue(), kiteAttrValue.getAttrValue())).findAny().map(KiteAttrValue::getAttrValueDesc).orElse(null);
                                    if(KiteStringUtils.isNotEmpty(valueDesc)) {
                                        attr.setValueDesc(valueDesc);
                                    }
                                }
                            });
                            KiteOfferInst additionalKiteOfferInst = querySceneInstService.getOfferInst(custId, kiteInst.getInstId());
                            operateSceneInstService.addAdditionalOfferInst(sceneInstId, additionalKiteOfferInst);
                        } else {
                            operateSceneAdditionalOfferInstService.removeAdditionalOfferInst(sceneInstId, kiteInst.getInstId(), custId, null);
                        }
                    });
                }
            }
        }

        // 点击操作类型触发公共属性联动
        List<KiteAttr> commonAttrs = querySceneInstService.listCommonAttrs(sceneInstId);
        commonAttrs= commonAttrs.stream().filter(d ->
            KiteStringUtils.equals("93",d.getModuleId())).collect(Collectors.toList());
        if (KiteListUtils.isNotEmpty(commonAttrs)) {
            commonAttrs.forEach(commonAttr -> {
                personAttrDealService.apply(commonAttr, sceneInstId, commonAttr.getFieldName(), commonAttr.getOriginValue(), commonAttr.getValueDesc());
            });
        }
        return ErrorConsts.SUCCESS.getResult(true);
    }
}
